const User = require('../models/user');

// 检查是否为管理员
const isAdmin = async (ctx, next) => {
    try {
        const user = await User.findByPk(ctx.state.user.id);
        if (user.roleId !== 1) {  // roleId 1 为管理员
            ctx.status = 403;
            ctx.body = {
                code: 403,
                errMsg: '权限不足'
            };
            return;
        }
        await next();
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            errMsg: '服务器错误'
        };
    }
};

// 检查是否为本人操作或管理员
const isSelfOrAdmin = async (ctx, next) => {
    try {
        const user = await User.findByPk(ctx.state.user.id);
        const targetUserId = parseInt(ctx.params.id);

        if (user.roleId !== 1 && user.id !== targetUserId) {
            ctx.status = 403;
            ctx.body = {
                code: 403,
                errMsg: '权限不足，只能操作本人信息'
            };
            return;
        }
        await next();
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 500,
            errMsg: '服务器错误'
        };
    }
};

module.exports = {
    isAdmin,
    isSelfOrAdmin
}; 